package com.itmck.config;

import com.alibaba.fastjson.JSON;
import com.itmck.pojo.User;
import com.itmck.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;

/**
 * 太阳当空照，花儿对我笑
 * <p>
 * Create by M ChangKe 2022/9/8 14:30
 * 创建MyRealm extends AuthorizingRealm 域用于管理用户的认证与授权。
 */
@Slf4j
public class CustomRealm extends AuthorizingRealm {


    @Resource
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        log.info("获取授权角色与权限:{}", JSON.toJSONString(principals));
        String userName = (String) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo();
        Map<String, Set<String>> mp = userService.getRolesAndPermissionsByUserName(userName);
        if (null != mp) {
            Set<String> permissions = mp.get("permissions");
            Set<String> roleNames = mp.get("roleNames");
            auth.setRoles(roleNames);
            auth.setStringPermissions(permissions);
            log.info("auth:{}", JSON.toJSONString(auth));
        }
        return auth;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("认证:{}", JSON.toJSONString(token));
        CustomToken customToken = (CustomToken) token;
        String loginType = customToken.getLoginType();
        log.info("当前登录类型:{}", loginType);
        String userName = (String) token.getPrincipal();//获取身份
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String password = String.valueOf(usernamePasswordToken.getPassword());
        User user = userService.getUserByUserName(userName);
        if (null == user) {
            return null;
        }
        if (user.getPassword().equals(password)) {
            log.info("登录成功");
            /**
             * SimpleAuthenticationInfo（Object principal, Object credentials, String realmName）构造参数
             * 第一个参数principal：身份。后续权限可以直接获取  String userName = (String) principals.getPrimaryPrincipal();
             * 第二个参数：密码
             * 第三个参数：当前类名
             *
             *
             */
            return new SimpleAuthenticationInfo(userName, password, getName());
        }
        return null;
    }

}
